import com.alibaba.fastjson.JSON;
import com.tc.classloader.MyClassLoad;
import com.tc.classloader.MyUrlClassLoad;
import com.tc.delayed.TaskQueueDaemonThread;
import com.tc.groovy.Configurator;
import com.tc.service.Impl.UserInfoSerivceImpl;
import com.tc.service.UserInfoSerivce;
//import com.vip.osp.proxy.StartProxy;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;

/**
 * Created by cai.tian on 2017/12/6.
 */
public class test4 {
    private final Logger logger = LoggerFactory.getLogger(test4.class);

    @Test
    public void demo1() {

        System.setProperty("VIP_CFGCENTER_ZK_CONNECTION", "10.198.195.147:2181,10.198.195.148:2181,10.198.195.149:2181");
        //System.setProperty("VIP_CFGCENTER_ZK_CONNECTION","10.108.28.27:2181");
        System.setProperty("APP_LISTEN_PORT", "2080");
        System.setProperty("JMX_PORT", "8061");
        System.setProperty("JAVA_OPTS", "-Dosp-proxy.logfile=..\\logs\\osp-proxy");
        String[] a = {"-port", "2080"};

        //StartProxy.main(a);

    }

    @Test
    public void demo2() throws Exception {

        List allSubclassOfTestInterface = getAllSubclassOfTestInterface(UserInfoSerivce.class);
        System.out.println(Thread.currentThread().getName() + JSON.toJSONString(allSubclassOfTestInterface));
        final Lock lock = new ReentrantLock();
        final Condition condition = lock.newCondition();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                UserInfoSerivceImpl u = new UserInfoSerivceImpl();
                List allSubclassOfTestInterface = getAllSubclassOfTestInterface(UserInfoSerivce.class);
                System.out.println(Thread.currentThread().getName() + JSON.toJSONString(allSubclassOfTestInterface));
                condition.signal();
                lock.unlock();
            }
        }).start();
        lock.lock();
        condition.await();

        allSubclassOfTestInterface = getAllSubclassOfTestInterface(UserInfoSerivce.class);
        System.out.println(Thread.currentThread().getName() + JSON.toJSONString(allSubclassOfTestInterface));
    }


    private List getAllSubclassOfTestInterface(Class cc) {
        Field field = null;
        Vector v = null;
        List<Class> allSubclass = new ArrayList<>();
        //ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        Class<?> classOfClassLoader = classLoader.getClass();
        while (classOfClassLoader != ClassLoader.class) {
            classOfClassLoader = classOfClassLoader.getSuperclass();
        }
        try {
            field = classOfClassLoader.getDeclaredField("classes");
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("无法获取到当前线程的类加载器的classes域!");
        }
        field.setAccessible(true);
        try {
            v = (Vector) field.get(classLoader);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("无法从类加载器中获取到类属性!");
        }
        for (int i = 0; i < v.size(); ++i) {
            Class<?> c = (Class<?>) v.get(i);
            if (cc.isAssignableFrom(c)) {
                allSubclass.add(c);
            }
        }
        return allSubclass;
    }


    @Test
    public void demo3() {

        try {
            //URL url = new URL("file:/F://testGradle//");
            MyClassLoad myloader = new MyClassLoad("F://testGradle//");
            Class c = myloader.loadClass("com.tc.test"); //硬盘上编译后的jar文件
            System.out.println("----------");
            Object o = c.newInstance();
            //((com.tc.test)o).sey();
            Method demo = o.getClass().getMethod("demo");
            demo.invoke(o);

            System.out.println(o.getClass());
            List allSubclassOfTestInterface = getAllSubclassOfTestInterface(o.getClass());
            System.out.println(Thread.currentThread().getName() + JSON.toJSONString(allSubclassOfTestInterface));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void demo6() throws Exception {
        File f = new File("src\\main\\resources\\my.groovy");
        Configurator c = new Configurator();
        c.run(f);
    }
    @Test
    public void demo4() throws Exception {
        URL url = new URL("file:/F://testGradle//");
        MyUrlClassLoad myUrlClassLoad = new MyUrlClassLoad(new URL[]{url});
        Class c = myUrlClassLoad.loadClass("com.tc.test"); //硬盘上编译后的jar文件

        Object o = c.newInstance();
        //((com.tc.test)o).sey();
        Method demo = o.getClass().getMethod("demo");
        demo.invoke(o);

        System.out.println(o.getClass());
        List allSubclassOfTestInterface = getAllSubclassOfTestInterface(o.getClass());
        System.out.println(Thread.currentThread().getName() + JSON.toJSONString(allSubclassOfTestInterface));
    }

    @Test
    public void demo5() throws Exception {
        logger.info("------tc---------");
    }



    @Test
    public void demo7() throws Exception {
        String targetfilePath = "D:\\1.xls";
        String sourcefilePath = "D:\\sql.xls";
        File file = new File(targetfilePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        try {
            //这一步跟创建只读的Excel一致。
            Workbook rw = Workbook.getWorkbook(new File(sourcefilePath));
            //这一步在原有文件的基础上新建一个文件
            WritableWorkbook wwb = Workbook.createWorkbook(file);
            //获得编号为2的sheet
            WritableSheet sheet2 = wwb.createSheet("name", 0);
            Sheet sheet = rw.getSheet(0);
            int columns = sheet.getColumns();
            int rows = sheet.getRows();
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++) {
                    Cell cell = sheet.getCell(j, i);

                    String decrypt = Aes.decrypt(cell.getContents());

                    Label lp = new Label(j, i, decrypt);
                    //添加
                    sheet2.addCell(lp);
                }
            }
            wwb.write();
            wwb.close();
            rw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void demo8() throws Exception {
        String decrypt = Aes.decrypt("B284A9E1EADF79CE290D74419F920AD6");
        System.out.println(decrypt);
        System.out.println(Aes.encrypt("麦迪努尔·热西提"));
    }

    @Test
    public void demo9() throws Exception {
        List<Integer> l = new ArrayList();

        l.add(1);
        l.add(2);
        l.add(3);
        l.add(20);

        Stream<Integer> integerStream = l.stream()
                .filter(p -> p > 10)
                .map(p -> p);


        Object[] objects = integerStream.toArray();
        l.add(30);
        //.forEach(age -> System.out.println(age));//相当于Function接口，map在这里是（函数）映射的意思
        System.out.println(objects.length);


    }

    @Test
    public void demo10() throws Exception {

        System.out.print(ThreadLocalRandom.current().nextLong(700, 800));

        //newProxyInstance()
    }

    @Test
    public void demo11() {

        System.out.println(System.getProperty("java.io.tmpdir").trim());
        System.out.println(Thread.currentThread().getName());
        //newProxyInstance()
    }


    @Test
    public void demo12() throws Exception {
        TaskQueueDaemonThread t = TaskQueueDaemonThread.getInstance();

        t.put(1000, () -> demo11());
        t.put(1500, () -> demo11());
        t.put(2000, () -> demo11());

        t.init();


        Thread.sleep(2002);
        System.out.print(System.getProperty("java.io.tmpdir").trim());

        //newProxyInstance()
    }


    @Test
    public void demo13() throws Exception {
       Exchanger<String> exgr = new Exchanger<String>();
        ExecutorService threadPool = Executors.newFixedThreadPool(2);

            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String A = "银行流水A";// A录入银行流水数据
                        String B=exgr.exchange(A);
                        System.out.println("A和B数据是否一致：" + A.equals(B) + "，A录入的是："
                                + A + "，B录入是：" + B);
                    } catch (InterruptedException e) {
                    }
                }
            });
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String B = "银行流水B";// B录入银行流水数据
                        String A = exgr.exchange(B);
                        System.out.println("A和B数据是否一致：" + A.equals(B) + "，A录入的是："
                                + A + "，B录入是：" + B);
                    } catch (InterruptedException e) {
                    }
                }
            });
            threadPool.shutdown();

            System.out.println(Runtime.getRuntime().availableProcessors());
        //List<Runnable> runnables = threadPool.shutdownNow();
        //newProxyInstance()
    }


    @Test
    public void demo14() throws Exception {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = sdf.parse("2018-06-09 09:40:00");
        Date parse1 = sdf.parse("2018-06-09 18:40:00");
        System.out.println(((parse1.getTime()-parse.getTime())/(long) (1000*60*60))+"");
    }


    @Test
    public void demo15() throws Exception {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date obegin = sdf.parse("2018-06-09 09:40:00");
        Date oend = sdf.parse("2018-08-09 18:40:00");
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
        sdf1.parse("2018-01-01");
        //Date x = new Date(1514851200000L);
       // Date y = new Date(1514851200000L);
        System.out.println(sdf.format(sdf1.parse("2018-01-01")));
        //System.out.println(sdf.format(y));
    }


    @Test
    public void demo17() throws Exception {
        String targetfilePath = "D:\\abc1.xls";
        String sourcefilePath = "D:\\abc.xls";
        File file = new File(targetfilePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        try {
            //这一步跟创建只读的Excel一致。
            Workbook rw = Workbook.getWorkbook(new File(sourcefilePath));
            //这一步在原有文件的基础上新建一个文件
            WritableWorkbook wwb = Workbook.createWorkbook(file,rw);
            //获得编号为2的sheet
            WritableSheet sheet2 = wwb.getSheet(0);
            //添加
            sheet2.addCell(new Label(1,26,""));

            wwb.write();
            wwb.close();
            rw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
